
export default class EventBus {

    private readonly events = new Map<string, Array<Function>>();

    constructor() {
    }

    public emit(eventName: string, data: any): void {
        let functions = this.events.get(eventName);
        if (functions) {
            functions.forEach(function (fn: Function) {
                fn(data);
            });
        }
    }

    public on(eventName: string, fn: Function) {
        let functions = this.events.get(eventName);
        if (functions) {
            functions.push(fn);
        } else {
            this.events.set(eventName, [fn]);
        }
    }

    public off(eventName: string, fn: Function) {
        let fns = this.events.get(eventName);
        if (fns) {
            for (let i = 0; i < fns.length; i++) {
                if (fns[i] === fn) {
                    fns.splice(i, 1);
                    break;
                }
            }
        }
    }
}
